<template>
  <el-dialog :title="titleMap[mode]" v-model="visible" :width="600" destroy-on-close @closed="$emit('closed')">
    <el-form :model="form" :rules="rules" :disabled="mode=='show'" ref="dialogForm" label-width="100px">
      <el-form-item label="上级部门" prop="parentId">
        <el-tree-select :check-strictly=true v-model="form.parentId" class="-input__inner" :render-after-expand="false" :data="groups"
                        :props="{label:'name'}" ref="tree" node-key="id" @node-click="handleNodeClick"/>
      </el-form-item>
      <el-form-item label="部门名称" class="inline" prop="name">
        <el-input v-model="form.name" placeholder="请输入部门名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="部门领导" class="inline" prop="leaderId" >
        <el-input v-model="form.leaderId" placeholder="领导人ID" clearable disabled>
          <template #append>
            <el-button icon="el-icon-Search"  @click="showLeader = true"/>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="联系人员" class="inline" prop="contact">
        <el-input v-model="form.contact" placeholder="请输入联系人姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="联系电话" class="inline" prop="mobile">
        <el-input v-model="form.mobile" placeholder="请输入联系人手机号" clearable></el-input>
      </el-form-item>
      <el-form-item label="联系人邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入联系人邮箱" clearable></el-input>
      </el-form-item>
      <el-form-item label="网址" prop="web">
        <el-input v-model="form.web" placeholder="请输入网址" clearable></el-input>
      </el-form-item>
      <el-form-item label="是否启用" prop="enabled">
        <el-radio-group v-model="form.enabled">
          <el-radio
            v-for="item in dicts.system_global_status"
            :key="item.v"
            :label="form.enabled == item.v ? form.enabled : item.v "
            :value="item.v"
          >
            {{ item.k }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="地址" prop="address">
        <el-input v-model="form.address" clearable type="textarea"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible=false">取 消</el-button>
      <el-button v-if="mode!='show'" type="primary" :loading="isSaveing" @click="submit()">保 存</el-button>
    </template>
  </el-dialog>


  <el-dialog v-model="showLeader" title="选择领导人" width="500px">
    <el-form :model="userForm" label-width="100px">
      <el-form-item label="用户名称" class="inline" prop="name">
        <el-input v-model="userForm.username" placeholder="请输入用户名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="真实姓名" class="inline" prop="contact">
        <el-input v-model="userForm.realName" placeholder="请输入真实姓名" clearable></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" class="inline" prop="mobile">
        <el-input v-model="userForm.email" placeholder="请输入用户邮箱" clearable></el-input>
      </el-form-item>
      <el-form-item label="手机号码" class="inline" prop="email">
        <el-input v-model="userForm.mobile" placeholder="请输入手机号码" clearable></el-input>
      </el-form-item>
      <el-form-item >
        <el-button type="primary" @click="searchUser" icon="el-icon-search">搜索</el-button>
        <el-button  @click="reset" icon="el-icon-refreshRight">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table width="100%" ref="table" row-key="id" :data="userData" border style="margin-bottom: 10px" stripe @selection-change="handleSelectionChange">
      <el-table-column align="center" width="55" type="selection">选择</el-table-column>
      <el-table-column label="机构名称" prop="username" width="200"></el-table-column>
      <el-table-column label="真实姓名" prop="realName"></el-table-column>
    </el-table>
    <el-footer style="display: flex;justify-content: center">
      <el-pagination
        :current-page="userForm.currentPage"
        :page-size="userForm.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-footer>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="showLeader = false">取消</el-button>
        <el-button type="primary" @click="confirmLeader">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
export default {
  computed: {
    id() {
      return id
    }
  },
  dicts: ['system_global_status'],
  emits: ['success', 'closed'],
  data() {
    return {

      multipleSelection:[],
      userData:[],
      mode: 'add',
      showLeader:false,
      total:1000,
      titleMap: {
        add: '新增机构',
        edit: '编辑机构',
        show: '查看机构'
      },
      visible: false,
      isSaveing: false,
      userForm:{
        current:1,
        size:10,
        username:'',
        realName:'',
        email:'',
        phone:'',
        gender:'',
        enabled:'',
        unitId:'',
      },
      //表单数据
      form: {
        id: "",
        parentId: "",
        name: "",
        contact: "",
        mobile: "",
        email: '',
        web: '',
        sort: 1,
        enabled: "1",
        leaderId: '',
        address: ""
      },
      //验证规则
      rules: {
        name: [
          {required: true, message: '部门名称不能为空！', trigger: 'blur'},
        ],
        parentId: [
          {required: true, message: '上级机构不能为空', change: 'blur'},
        ],
        mobile: [
          {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'}
        ],
        web: [
          {
            pattern: /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/,
            message: '请输入正确的网址',
            trigger: 'blur'
          }
        ],
        email: [
          {
            pattern: /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/,
            message: '请输入正确的邮箱',
            trigger: 'blur'
          }
        ]
      },
      //所需数据选项
      groups: [],
      //请求返回数据
      res: {}
    }
  },
  created() {
    this.getData()
  },
  mounted() {
    this.getGroup()
  },
  methods: {
    //领导人数据
    async getData(){
      let res = await this.$API.system.userManagement.list.get(this.userForm)
      this.userData = res.data.records
      this.total =res.data.total;
    },
    // 处理选择框勾选
    handleSelectionChange(val){
      // 单选
      if (val.length > 1) {
        this.$refs.table.clearSelection()
        this.$refs.table.toggleRowSelection(val.pop())
      }
      this.multipleSelection = val
    },
    // 领导人确定
    confirmLeader(){
      this.form.leaderId = this.multipleSelection[0].username
      this.showLeader=false
    },
    // 搜索
    searchUser(){
      this.getData(this.userForm)
    },
    // 重置
    reset(){
      this.userData = []
      this.userForm = {
        current:1,
        size:10,
        username:'',
        realName:'',
        email:'',
        phone:'',
        gender:'',
        enabled:'',
        unitId:'',
      }
      this.getData()
    },

    //点击节点
    handleNodeClick(data, checked) {
      if (checked) {
        this.$refs.tree.setCheckedNodes([data])
      }
    },
    //切换分页
    handleCurrentChange(e){
      this.userForm.current = e;
      this.getData()
    },
    // 改变单页显示数量
    handleSizeChange(e){
      this.userForm.size = e
      this.getData()
    },

    //显示
    open(mode = 'add') {
      this.mode = mode;
      this.visible = true;
      return this
    },

    //加载树数据
    async getGroup() {
      var res = await this.$API.system.unit.tree.get();
      this.groups = res.data;
    },

    //表单提交方法
    submit() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          this.isSaveing = true;
          let res = {};
          if (this.mode == 'add') {
            res = await this.$API.system.unit.addUnit.post(this.form)
          } else {
            res = await this.$API.system.unit.updateUnit.post(this.form);
          }
          this.isSaveing = false;
          if (res.code == 200) {
            this.$emit('success', this.form, this.mode)
            this.visible = false;
            this.$message.success("操作成功")
          } else {
            this.$alert(res.message, "提示", {type: 'error'})
          }
        }
      })
    },
    //表单注入数据
    async setData(id) {
      if(id){
        let res = await this.$API.system.unit.detail.get(id)
        this.form = res.data
      } else{
        this.form.enabled = 1
      }



      //可以和上面一样单个注入，也可以像下面一样直接合并进去
      //Object.assign(this.form, data)
    }
  }
}
</script>

<style scoped>
.inline {
  display: inline-flex;
  vertical-align: middle;
  width: 50%;
}

.-input__inner {
  width: 100%;
}
:deep(.el-table__header-wrapper .el-table-column--selection>.cell){
  display: none;
}
</style>
